package com.order.config;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.io.InputStream;

@Configuration
@Data
public class QiNiuYunConfig {

    @Value("${qiniu.accessKey}")
    private String accessKey;

    @Value("${qiniu.secretKey}")
    private String secretKey;

    @Value("${qiniu.bucket}")
    private String bucket;

    @Value("${qiniu.webPath}")
    public String webPath = "http://t0vms2noi.hd-bkt.clouddn.com"; // 移除末尾斜杠

    /**
     * 上传文件到七牛云
     * @param file 输入流
     * @param filename 文件名
     * @return 上传后的URL，失败时返回null
     */
    public String uploadImgToQiNiu(InputStream file, String filename) {
        // 根据实际存储区域选择，zone0:华东, zone1:华北, zone2:华南, na0:北美
        com.qiniu.storage.Configuration cfg = new com.qiniu.storage.Configuration(Zone.zone0());
        UploadManager uploadManager = new UploadManager(cfg);

        try {
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            Response response = uploadManager.put(file, filename, upToken, null, null);

            // 检查响应状态
            if (!response.isOK()) {
                System.err.println("七牛云上传失败，响应状态: " + response.statusCode);
                return null;
            }

            // 解析上传结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

            // 正确拼接URL（webPath末尾无斜杠，这里添加）
            return webPath + "/" + putRet.key;

        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println("七牛云异常: " + r.toString());
            try {
                System.err.println("错误详情: " + r.bodyString());
            } catch (QiniuException ex2) {
                ex2.printStackTrace();
            }
        } catch (Exception e) {
            System.err.println("上传发生异常:");
            e.printStackTrace();
        }

        return null;
    }
}
